//
//  GaugeViewController.m
//  P2P
//
//  Created by Cindy on 15/12/21.
//  Copyright (c) 2015年 EIMS. All rights reserved.
//

#import "GaugeViewController.h"
#import "CommonClass.h"
#define IS_iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)

#define IS_iPhone6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? (CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) || CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size)) : NO)

#define IS_iPhone6plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? (CGSizeEqualToSize(CGSizeMake(1125, 2001), [[UIScreen mainScreen] currentMode].size) || CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size)) : NO)
#define IS_iOS7 ( [[[UIDevice currentDevice]systemVersion] floatValue] < 8.0)

#define OriginValueX (320.0f)
#define OriginValueY (290.0f)

#define initX ((OriginValueX-260)/2)
#define initY ((OriginValueY+7)/2)

#define centerX (OriginValueX/2)
#define centerY (OriginValueY/2)


#define circleR (486.0/2/2)

#define imgOffsetAngel (atan((centerX-initX-100)/(initY-centerY)))

#define czstartAngle (M_PI_2+atan((centerX-initX)/(initY-centerY))-0.17)

#define czendAngle (czstartAngle+M_PI*2)

#define ViewWidth (self.view.frame.size.width)

#define animationDuration 2.0

#define hundredTime (animationDuration*0.51)

#define TwentyColor ([UIColor colorWithRed:225.0/255 green:39.0/255 blue:39.0/255 alpha:1])
#define FourtyColor ([UIColor colorWithRed:233.0/255 green:117.0/255 blue:40.0/255 alpha:1])


@interface GaugeViewController ()
{
    CALayer *rectLayer;
    
    UIImageView *imagView;
    
    NSTimer *timer;
    
    CGFloat targetTimer;
    
    IBOutlet UIView *headView;
    
    IBOutlet UILabel *scoreLB;
    
    BOOL timeEnd;
    
    
    IBOutlet UIView *pointView;
    
    CGFloat totalAngel;
    
    CGFloat stepAngel;
}
@property (nonatomic, strong) CAShapeLayer *gaugeCircleLayer;

@end

@implementation GaugeViewController

- (void)dealloc
{
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    targetTimer=0;
    
    [self initRectLayer];
    
    [pointView addSubview:imagView];
    
}

- (void)setScore:(NSString *)score
{
    _score=score;
    
    //100-3.53 80-2.78 60-2.08 40 -1.38 20-0.68
    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:@"3.53",@"100",@"2.78",@"80",@"2.08",@"60",@"1.40",@"40",@"0.68",@"20", nil];
    
    totalAngel=[[dic objectForKey:self.score] floatValue];
    
    stepAngel=0.01;
    
    [CommonClass completion:^(bool finish) {
        
        [self startCircle:0];
        
    } afterDelay:1];
    
}

- (void)startCircle:(CGFloat)angel
{
    if(angel+stepAngel>totalAngel)
        angel=totalAngel;
    
    scoreLB.text=[NSString stringWithFormat:@"%.0f",[self.score floatValue]*angel/totalAngel];
    NSArray *textColors=[NSArray arrayWithObjects:TwentyColor,FourtyColor,SixtyColor,EightyColor,HundredColor,nil];
    
    NSInteger index=angel/3.53/0.2;
    scoreLB.textColor=[textColors objectAtIndex:index];

    
    [UIView animateWithDuration:0.01 animations:^{
        
        pointView.transform = CGAffineTransformMakeRotation(angel);
        
    } completion:^(BOOL finished) {
        
        //        NSLog(@"kao");
        
        if(angel<totalAngel)
        {
            
            if(angel/totalAngel<0.5)
                stepAngel=stepAngel+angel/totalAngel*0.003;
            else
                stepAngel=stepAngel-(1-angel/totalAngel)*0.003;
            
            [self startCircle:angel+stepAngel];
        }
        else
        {
            scoreLB.text=[NSString stringWithFormat:@"%.0f",[self.score floatValue]];
        }
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self stopTimer];
}
- (void)viewDidLayoutSubviews
{
    if(IS_iPhone5)
    {
        
    }
    else if(IS_iPhone6)
        headView.frame=CGRectMake(25, headView.frame.origin.y, headView.frame.size.width, headView.frame.size.height);
    else if(IS_iPhone6plus)
        headView.frame=CGRectMake(40, headView.frame.origin.y, headView.frame.size.width, headView.frame.size.height);
    
    
    pointView.backgroundColor=[UIColor clearColor];
    //    pointView.layer.borderWidth=1;
    pointView.layer.borderColor=[UIColor greenColor].CGColor;
    //    pointView.layer.cornerRadius=circleR;
    pointView.frame=CGRectMake(0, 0, circleR*2, circleR*2);
    [pointView setCenter:CGPointMake(centerX, centerY)];
    imagView.frame=CGRectMake(-10, IS_iOS7?122:118, imagView.frame.size.width, imagView.frame.size.height);
    
    /*
     if(!self.gaugeCircleLayer)
     {
     self.gaugeCircleLayer=[CAShapeLayer layer];
     
     [headView.layer addSublayer:self.gaugeCircleLayer];
     
     self.gaugeCircleLayer.lineWidth = 1;
     self.gaugeCircleLayer.fillColor = [UIColor clearColor].CGColor;
     self.gaugeCircleLayer.strokeColor = [UIColor blueColor].CGColor;
     self.gaugeCircleLayer.path = [self insideCirclePath].CGPath;
     }
     */
}


- (UIBezierPath *)insideCirclePath {
    
    CGPoint arcCenter = CGPointMake(centerX,centerY);
    
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:arcCenter
                                                        radius:circleR
                                                    startAngle:czstartAngle
                                                      endAngle:czendAngle
                                                     clockwise:YES];
    
    //
    return path;
}



- (void)initRectLayer
{
    imagView=[[UIImageView alloc] initWithFrame:CGRectMake(initX, initY, 35, 35)];
    imagView.contentMode=UIViewContentModeScaleAspectFit;
    imagView.image=[UIImage imageNamed:@"point"];
    
    CGAffineTransform transformViewImg=CGAffineTransformMakeRotation(imgOffsetAngel);
    imagView.transform=transformViewImg;
    
    scoreLB.textColor = TwentyColor;
    //    rectLayer = imagView.layer;
    //    rectLayer.frame = CGRectMake(initX, initY, 35, 35);
    //    rectLayer.delegate=self;
    //     rectLayer.cornerRadius = 15;
    //     rectLayer.backgroundColor = [[UIColor blackColor] CGColor];
    //    [headView.layer addSublayer:rectLayer];
    
}

- (void)startPointAction
{
    CAKeyframeAnimation *rectRunAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGAffineTransform transformView=CGAffineTransformIdentity;
    //     CGPathMoveToPoint(path, NULL, initX, initY);
    //     CGPathAddArc(path, &transformView, centerX, centerY, circleR, M_PI_2+atan((centerX-initX)/(initY-centerY)), M_PI*2+atan((initY-centerY)/(centerX-initX))+M_PI/6, NO);
    ////
    CGPathAddArc(path, &transformView, centerX, centerY, circleR,czstartAngle ,czendAngle, NO);
    
    //     CGPathAddArc(CGMutablePathRef path, const CGAffineTransform *m,
    //                                 CGFloat x, CGFloat y, CGFloat radius, CGFloat startAngle, CGFloat endAngle,
    //                                 bool clockwise)
    
    //设定关键帧位置，必须含起始与终止位置
    //     rectRunAnimation.values = @[[NSValue valueWithCGPoint:rectLayer.frame.origin],
    //                                 [NSValue valueWithCGPoint:CGPointMake(ViewWidth-15 ,
    //                                                                       rectLayer.frame.origin.y)],
    //                                 [NSValue valueWithCGPoint:CGPointMake(ViewWidth-15 ,
    //                                                                       rectLayer.frame.origin.y + 100)],
    //                                 [NSValue valueWithCGPoint:CGPointMake(15, rectLayer.frame.origin.y + 100)],
    //                                 [NSValue valueWithCGPoint:rectLayer.frame.origin]];
    
    rectRunAnimation.path = path;
    CFRelease(path);
    
    //设定每个关键帧的时长，如果没有显式地设置，则默认每个帧的时间=总duration/(values.count - 1)
    //     rectRunAnimation.keyTimes = @[[NSNumber numberWithFloat:0.0], [NSNumber numberWithFloat:0.6],
    //                                   [NSNumber numberWithFloat:0.7], [NSNumber numberWithFloat:0.8],
    //                                   [NSNumber numberWithFloat:1]];
    //     rectRunAnimation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
    //                                          [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear],
    //                                          [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear],
    //                                          [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
    rectRunAnimation.repeatCount = 0;
    rectRunAnimation.autoreverses = NO;
    rectRunAnimation.calculationMode = kCAAnimationLinear;
    rectRunAnimation.duration = animationDuration;
    [rectLayer addAnimation:rectRunAnimation forKey:@"rectRunAnimation"];
    
    
    
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI*2+imgOffsetAngel];
    rotationAnimation.duration = animationDuration;
    rotationAnimation.cumulative = NO;
    rotationAnimation.repeatCount = 0;
    [rectLayer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

-(void)pauseLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}



- (IBAction)start:(id)sender {
    
    [self startPointAction];
    
    [self startTimer];
}


- (IBAction)stop:(id)sender {
    
    [self pauseLayer:rectLayer];
    
    [self stopTimer];
    
}


- (void)startTimer
{
    //    if(timer==nil)
    //    {
    //        timer=  [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(calculateAcr) userInfo:nil repeats:YES];
    //
    //    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        while (!timeEnd)
        {
            //            @synchronized(@"timeCal")
            {
                [NSThread sleepForTimeInterval:0.01];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self calculateAcr];
            });
        }
    });
    
    
    
}
- (void)stopTimer
{
    if(timer)
    {
        [timer invalidate];
        timer=nil;
    }
    timeEnd=YES;
}
- (void)calculateAcr
{
    targetTimer+=0.01;
    
    if(targetTimer>=[self.score floatValue]*hundredTime/100)
    {
        [self pauseLayer:rectLayer];
        [self stopTimer];
        
    }
    
    scoreLB.text=[NSString stringWithFormat:@"%.0f",(targetTimer*100/hundredTime>[self.score floatValue])?[self.score floatValue]:targetTimer*100/hundredTime];
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
